package com.foodcommunity.service.impl;

import com.foodcommunity.common.Result;
import com.foodcommunity.dto.RestaurantReviewDTO;
import com.foodcommunity.entity.Restaurant;
import com.foodcommunity.entity.RestaurantReview;
import com.foodcommunity.mapper.RestaurantMapper;
import com.foodcommunity.mapper.RestaurantReviewMapper;
import com.foodcommunity.service.RestaurantService;
import com.foodcommunity.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RestaurantServiceImpl implements RestaurantService {

    @Autowired
    private RestaurantMapper restaurantMapper;
    
    @Autowired
    private RestaurantReviewMapper restaurantReviewMapper;

    @Override
    public List<Map<String, Object>> getHotRestaurants() {
        // 使用RestaurantMapper中的selectHotRestaurantsRanking方法获取热门餐厅排行榜
        return restaurantMapper.selectHotRestaurantsRanking(10);
    }
    
    @Override
    public Result<Restaurant> getRestaurantDetail(Long id) {
        Restaurant restaurant = restaurantMapper.selectById(id);
        if (restaurant == null) {
            return Result.error("餐厅不存在");
        }
        return Result.success(restaurant);
    }
    
    @Override
    @Transactional
    public Result<Restaurant> addRestaurant(Restaurant restaurant) {
        // 设置默认评分为5.0
        if (restaurant.getRating() == null) {
            restaurant.setRating(5.0);
        }
        
        int rows = restaurantMapper.insert(restaurant);
        if (rows > 0) {
            return Result.success(restaurant);
        }
        return Result.error("添加餐厅失败");
    }
    
    @Override
    @Transactional
    public Result<Restaurant> updateRestaurant(Restaurant restaurant) {
        Restaurant existingRestaurant = restaurantMapper.selectById(restaurant.getId());
        if (existingRestaurant == null) {
            return Result.error("餐厅不存在");
        }
        
        int rows = restaurantMapper.update(restaurant);
        if (rows > 0) {
            return Result.success(restaurant);
        }
        return Result.error("更新餐厅失败");
    }
    
    @Override
    @Transactional
    public Result<Void> deleteRestaurant(Long id) {
        Restaurant restaurant = restaurantMapper.selectById(id);
        if (restaurant == null) {
            return Result.error("餐厅不存在");
        }
        
        int rows = restaurantMapper.delete(id);
        if (rows > 0) {
            return Result.success(null);
        }
        return Result.error("删除餐厅失败");
    }
    
    @Override
    public Map<String, Object> getRestaurantsWithPage(int page, int size) {
        int offset = (page - 1) * size;
        List<Restaurant> restaurants = restaurantMapper.selectWithPage(offset, size);
        int total = restaurantMapper.count();
        
        Map<String, Object> result = new HashMap<>();
        result.put("restaurants", restaurants);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getRestaurantsByCondition(String cuisineType, Integer minPrice, 
                                                      Integer maxPrice, Double minRating, 
                                                      int page, int size) {
        int offset = (page - 1) * size;
        List<Restaurant> restaurants = restaurantMapper.selectByCondition(
                cuisineType, minPrice, maxPrice, minRating, offset, size);
        int total = restaurantMapper.countByCondition(cuisineType, minPrice, maxPrice, minRating);
        
        Map<String, Object> result = new HashMap<>();
        result.put("restaurants", restaurants);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }
    
    @Override
    @Transactional
    public Result<RestaurantReview> addRestaurantReview(RestaurantReviewDTO reviewDTO, Long userId) {
        // 验证餐厅是否存在
        Restaurant restaurant = restaurantMapper.selectById(reviewDTO.getRestaurantId());
        if (restaurant == null) {
            return Result.error("餐厅不存在");
        }
        
        // 处理图片URL
        String images = null;
        if (reviewDTO.getImageUrls() != null && reviewDTO.getImageUrls().length > 0) {
            images = String.join(",", reviewDTO.getImageUrls());
        }
        
        // 创建评论
        RestaurantReview review = new RestaurantReview();
        review.setRestaurantId(reviewDTO.getRestaurantId());
        review.setUserId(userId);
        review.setContent(reviewDTO.getContent());
        review.setRating(reviewDTO.getRating());
        review.setCreateTime(LocalDateTime.now());
        review.setImages(images);
        
        int rows = restaurantReviewMapper.insert(review);
        if (rows > 0) {
            // 更新餐厅评分
            Double avgRating = restaurantReviewMapper.calculateAverageRating(reviewDTO.getRestaurantId());
            if (avgRating != null) {
                restaurantMapper.updateRating(reviewDTO.getRestaurantId(), avgRating);
            }
            return Result.success(review);
        }
        return Result.error("评论失败");
    }
    
    @Override
    @Transactional
    public Result<Void> deleteRestaurantReview(Long id, Long userId) {
        RestaurantReview review = restaurantReviewMapper.selectById(id);
        if (review == null) {
            return Result.error("评论不存在");
        }
        
        // 验证是否是评论作者
        if (!review.getUserId().equals(userId)) {
            return Result.error("无权删除此评论");
        }
        
        int rows = restaurantReviewMapper.delete(id);
        if (rows > 0) {
            // 更新餐厅评分
            Double avgRating = restaurantReviewMapper.calculateAverageRating(review.getRestaurantId());
            if (avgRating != null) {
                restaurantMapper.updateRating(review.getRestaurantId(), avgRating);
            } else {
                // 如果没有评论了，设置默认评分
                restaurantMapper.updateRating(review.getRestaurantId(), 5.0);
            }
            return Result.success(null);
        }
        return Result.error("删除失败");
    }
    
    @Override
    public List<RestaurantReview> getRestaurantReviews(Long restaurantId) {
        return restaurantReviewMapper.selectByRestaurantId(restaurantId);
    }
    
    @Override
    public Map<String, Object> getRestaurantReviewsWithPage(Long restaurantId, int page, int size) {
        int offset = (page - 1) * size;
        List<RestaurantReview> reviews = restaurantReviewMapper.selectByRestaurantIdWithPage(
                restaurantId, offset, size);
        int total = restaurantReviewMapper.countByRestaurantId(restaurantId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("reviews", reviews);
        result.put("total", total);
        result.put("page", page);
        result.put("size", size);
        
        return result;
    }
    
    @Override
    public List<RestaurantReview> getUserRestaurantReviews(Long userId) {
        return restaurantReviewMapper.selectByUserId(userId);
    }

    @Override
    public int getRestaurantReviewCount(Long restaurantId) {
        return restaurantReviewMapper.countByRestaurantId(restaurantId);
    }

    @Override
    public List<Restaurant> getRestaurantsInArea(Double northLat, Double southLat, Double eastLng, Double westLng,
                                               String cuisineType, Integer minPrice, Integer maxPrice, Double minRating) {
        return restaurantMapper.selectInArea(northLat, southLat, eastLng, westLng, 
                                            cuisineType, minPrice, maxPrice, minRating);
    }
} 